package android.slc.ml.callback;

import android.database.Cursor;
import android.slc.ml.bean.i.IBaseResult;
import android.slc.ml.bean.i.IPropertyFile;
import android.slc.ml.utils.MediaLoaderThreadUtils;

import androidx.annotation.MainThread;
import androidx.loader.content.Loader;

/**
 * Created by Taurus on 2017/5/23.
 */

public abstract class OnBaseLoaderCallBack<T extends IBaseResult<?, ?>> implements OnLoaderCallBack {
    protected IPropertyFile mFileProperty;

    public OnBaseLoaderCallBack() {
    }

    public OnBaseLoaderCallBack(IPropertyFile fileProperty) {
        this.mFileProperty = fileProperty;
    }

    @Override
    public void onLoadFinish(Loader<Cursor> loader, Cursor data, OnDestroyLoaderCallback onDestroyLoaderCallback) {
        MediaLoaderThreadUtils.executeByCpu(new BaseLoaderCallBackTask<T>() {
            @Override
            public T doInBackground() {
                return generateResultDoInBackground(loader, data);
            }

            @Override
            public void onSuccess(T result) {
                onResult(result);
            }

            @Override
            protected void onDone() {
                super.onDone();
                onDestroyLoaderCallback.onDestroyLoader();
            }
        });

    }

    /**
     *
     * @param loader
     * @param data 不应该手动调用close，系统内部会调用
     * @return
     */
    protected abstract T generateResultDoInBackground(Loader<Cursor> loader, Cursor data);

    @MainThread
    public abstract void onResult(T result);

    @Override
    public String getSelections() {
        if (mFileProperty != null) {
            return mFileProperty.createSelection();
        }
        return null;
        //return "(" + MediaStore.MediaColumns.SIZE + " > ? )";
    }

    @Override
    public String[] getSelectionsArgs() {
        if (mFileProperty != null) {
            return mFileProperty.createSelectionArgs();
        }
        return null;
        //return new String[]{"0"};
    }

    @Override
    public String getSortOrderSql() {
        if (mFileProperty != null) {
            return mFileProperty.createSortOrderSql();
        }
        return null;
        //return MediaStore.MediaColumns.DATE_MODIFIED + " DESC";
    }

    public static abstract class BaseLoaderCallBackTask<T extends IBaseResult<?, ?>> extends MediaLoaderThreadUtils.Task<T> {

        @Override
        public void onCancel() {
            onSuccess(null);
        }

        @Override
        public void onFail(Throwable t) {
            t.printStackTrace();
            onSuccess(null);
        }

        @Override
        protected void onDone() {
            super.onDone();
        }
    }
}
